package com.tjec.project.businessWorkbench.service.impl;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.tjec.common.constant.AttachmentConstants;
import com.tjec.common.constant.Constants;
import com.tjec.common.enums.CatalogType;
import com.tjec.common.utils.DateUtils;
import com.tjec.common.utils.ServletUtils;
import com.tjec.framework.security.service.TokenService;

import com.tjec.project.system.service.IBmsAttachmentProjectBusinessService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.tjec.project.businessWorkbench.mapper.BmsBusinessPickupMapper;
import com.tjec.project.businessWorkbench.domain.BmsBusinessPickup;
import com.tjec.project.businessWorkbench.domain.BmsProjectDocCatalog;
import com.tjec.project.businessWorkbench.dto.BmsAttachmentDto;
import com.tjec.project.businessWorkbench.dto.BmsPickupTimerDto;
import com.tjec.project.businessWorkbench.service.IBmsBusinessPickupService;
import com.tjec.project.businessWorkbench.service.IBmsProjectDocCatalogService;
import com.tjec.project.system.domain.BmsAttachment;
import com.tjec.project.system.mapper.BmsAttachmentMapper;
import com.tjec.project.system.service.impl.SysUserServiceImpl;

/**
 * 收资管理Service业务层处理
 * 
 * @author pangyongfeng
 * @date 2020-04-24
 */
@Service
public class BmsBusinessPickupServiceImpl implements IBmsBusinessPickupService {
	private static final Logger log = LoggerFactory.getLogger(BmsBusinessPickupServiceImpl.class);

	@Autowired
	private BmsBusinessPickupMapper bmsBusinessPickupMapper;

	@Autowired
	private BmsAttachmentMapper bmsAttachmentMapper;

	@Autowired
	private IBmsAttachmentProjectBusinessService bmsAttachmentProjectBusinessService;

	@Autowired
	private TokenService tokenService;

	@Autowired
	private IBmsProjectDocCatalogService bmsProjectDocCatalogService;
	@Value("${sftp.http}")
	private String http;
	@Value("${sftp.ip}")
	private String ip;
	/**
	 * 查询收资管理
	 * 
	 * @param guid 收资管理ID
	 * @return 收资管理
	 */
	@Override
	public BmsBusinessPickup selectBmsBusinessPickupByGuid(String guid) {
		BmsBusinessPickup result = bmsBusinessPickupMapper.selectBmsBusinessPickupByGuid(guid);
		 if (result != null && result.getAttachments() != null && result.getAttachments().size() == 1 && result.getAttachments().get(0).getFileId() == null) {
	            result.setAttachments(null);
	        }else {
	        	result.getAttachments().forEach(it -> {
	                if (StringUtils.isNotBlank(it.getFileId())) {
	                    it.setStoragePath(http + ip + Constants.RESOURCE_PREFIX + it.getStoragePath());
	                }
	            });
	        }
		return result;
	}

	/**
	 * 查询收资管理列表
	 * 
	 * @param bmsBusinessPickup 收资管理
	 * @return 收资管理
	 */
	@Override
	public List<BmsBusinessPickup> selectBmsBusinessPickupList(BmsBusinessPickup bmsBusinessPickup) {
		List<BmsBusinessPickup> list = bmsBusinessPickupMapper.selectBmsBusinessPickupList(bmsBusinessPickup);
		list.forEach(item -> {
			List<BmsAttachmentDto> attachments = item.getAttachments();
			attachments.forEach(it -> {
				if (StringUtils.isNotBlank(it.getFileId())) {
					it.setStoragePath(http + ip +Constants.RESOURCE_PREFIX + it.getStoragePath());
	            }
			});
            
        });
		return list;
	}

	/**
	 * 新增收资管理
	 * 
	 * @param bmsBusinessPickup 收资管理
	 * @return 结果
	 * @throws Exception
	 */
	@Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public int insertBmsBusinessPickup(BmsBusinessPickup bmsBusinessPickup) throws Exception {
		
		//bmsProjectDocCatalogService.addDocCatalog(bmsBusinessPickup.getBusinessId(),CatalogType.ZERO.getCode());
		bmsBusinessPickup.setCreateTime(DateUtils.getNowDate());
		int res = bmsBusinessPickupMapper.insertBmsBusinessPickup(bmsBusinessPickup);
		if (res <= 0)
			throw new Exception("收资管理添加失败！");
		if (bmsBusinessPickup.getAttachmentIds() != null && bmsBusinessPickup.getAttachmentIds().size() > 0 && !"".equals(bmsBusinessPickup.getInveSurvey()) && bmsBusinessPickup.getInveSurvey()!=null) {
			int updateRes = bmsAttachmentMapper.updateBmsAttachmentByGuidsUpdateBiz(
					bmsBusinessPickup.getAttachmentIds(), bmsBusinessPickup.getGuid(),
					AttachmentConstants.BUSINESS_PICKUP, tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
			bmsAttachmentProjectBusinessService.insertBmsAttachmentProjectBusinessByBusinessId(bmsBusinessPickup.getAttachmentIds(), bmsBusinessPickup.getBusinessId());
			BmsBusinessPickup pickup = new BmsBusinessPickup();
			pickup.setGuid(bmsBusinessPickup.getGuid());
			pickup.setPickUpDate(DateUtils.getNowDate());
			pickup.setPickUpPerson(tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getNickName());
			pickup.setLastDate(bmsBusinessPickup.getLastDate());
			pickup.setInveSurvey(bmsBusinessPickup.getInveSurvey());
			pickup.setPickUpExplain(bmsBusinessPickup.getPickUpExplain());
			bmsBusinessPickupMapper.updateBmsBusinessPickup(pickup);
			return updateRes;
		}else if(bmsBusinessPickup.getAttachmentIds() != null && bmsBusinessPickup.getAttachmentIds().size() > 0 && ("".equals(bmsBusinessPickup.getInveSurvey()) || bmsBusinessPickup.getInveSurvey()==null)) {
			int updateRes = bmsAttachmentMapper.updateBmsAttachmentByGuidsUpdateBiz(
					bmsBusinessPickup.getAttachmentIds(), bmsBusinessPickup.getGuid(),
					AttachmentConstants.BUSINESS_PICKUP, tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
			bmsAttachmentProjectBusinessService.insertBmsAttachmentProjectBusinessByBusinessId(bmsBusinessPickup.getAttachmentIds(), bmsBusinessPickup.getBusinessId());
			BmsBusinessPickup pickup = new BmsBusinessPickup();
			pickup.setGuid(bmsBusinessPickup.getGuid());
			pickup.setPickUpDate(DateUtils.getNowDate());
			pickup.setPickUpPerson(tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getNickName());
			pickup.setLastDate(bmsBusinessPickup.getLastDate());
			pickup.setInveSurvey(bmsBusinessPickup.getInveSurvey());
			pickup.setPickUpExplain(bmsBusinessPickup.getPickUpExplain());
			bmsBusinessPickupMapper.updateBmsBusinessPickup(pickup);
			return updateRes;
		}else if(!"".equals(bmsBusinessPickup.getInveSurvey()) && bmsBusinessPickup.getInveSurvey()!=null && (bmsBusinessPickup.getAttachmentIds() == null || bmsBusinessPickup.getAttachmentIds().size() <= 0)) {
			
			BmsBusinessPickup pickup = new BmsBusinessPickup();
			pickup.setGuid(bmsBusinessPickup.getGuid());
			pickup.setPickUpDate(DateUtils.getNowDate());
			pickup.setPickUpPerson(tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getNickName());
			pickup.setLastDate(bmsBusinessPickup.getLastDate());
			pickup.setInveSurvey(bmsBusinessPickup.getInveSurvey());
			pickup.setPickUpExplain(bmsBusinessPickup.getPickUpExplain());
			int updateRes = bmsBusinessPickupMapper.updateBmsBusinessPickup(pickup);
			return updateRes;
		}else {
			return res;
		}
	}
	
	/*public void addDocCatalog(String businessId) {
		// 1、首先判断项目文档中第二级目录有没有收资管理目录
		// 1.） 如果没有，则在项目文档中添加第二级目录收资管理目录
		// 2.） 如果有，则不需要任何操作
		int isFlag = bmsProjectDocCatalogService.checkDocCatalog(businessId,"0");
		if (isFlag <= 0) {
			BmsProjectDocCatalog bmsProjectDocCatalog = new BmsProjectDocCatalog();
			bmsProjectDocCatalog.setBusinessId(businessId);
			bmsProjectDocCatalog.setParentId("0");
			List<BmsProjectDocCatalog> docCatalogs = bmsProjectDocCatalogService
					.selectBmsProjectDocCatalogList(bmsProjectDocCatalog);
			if (docCatalogs != null && docCatalogs.size() > 0) {
				BmsProjectDocCatalog docCatalog = new BmsProjectDocCatalog();
				docCatalog.setParentId(docCatalogs.get(0).getGuid());
				docCatalog.setName("收资管理");
				docCatalog.setSort(new Double(9999));
				docCatalog.setBusinessId(businessId);
				docCatalog.setIsEdit("0");
				bmsProjectDocCatalogService.insertBmsProjectDocCatalog(docCatalog);
			}
		}
	}*/

	/**
	 * 修改收资管理
	 * 
	 * @param bmsBusinessPickup 收资管理
	 * @return 结果
	 * @throws Exception
	 */
	@Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public int updateBmsBusinessPickup(BmsBusinessPickup bmsBusinessPickup) throws Exception {
		int result = 0;
		if("1".equals(bmsBusinessPickup.getFlag())) {//修改最迟日期
			bmsBusinessPickup.setUpdateTime(DateUtils.getNowDate());
			bmsBusinessPickup.setUpdateBy(tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getNickName());
			result = bmsBusinessPickupMapper.updateBmsBusinessPickup(bmsBusinessPickup);
		}else {//编辑按钮触发
			bmsBusinessPickup.setUpdateTime(DateUtils.getNowDate());
			result = bmsBusinessPickupMapper.updateBmsBusinessPickup(bmsBusinessPickup);
			if (result <= 0)
				throw new Exception("收资管理修改失败！");
			
			String[] guIds = {bmsBusinessPickup.getGuid()};
			bmsAttachmentMapper.updateBmsAttachmentByGuids(guIds, tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
			
			if (bmsBusinessPickup.getAttachmentIds() != null && bmsBusinessPickup.getAttachmentIds().size() > 0 && !"".equals(bmsBusinessPickup.getInveSurvey()) && bmsBusinessPickup.getInveSurvey()!=null) {
				int updateRes = bmsAttachmentMapper.updateBmsAttachmentByGuidsUpdateBiz(
						bmsBusinessPickup.getAttachmentIds(), bmsBusinessPickup.getGuid(),
						AttachmentConstants.BUSINESS_PICKUP, tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
				bmsAttachmentProjectBusinessService.insertBmsAttachmentProjectBusinessByBusinessId(bmsBusinessPickup.getAttachmentIds(), bmsBusinessPickup.getBusinessId());
				
				bmsBusinessPickup.setPickUpDate(DateUtils.getNowDate());
				bmsBusinessPickup.setPickUpPerson(tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getNickName());
				
				bmsBusinessPickupMapper.updateBmsBusinessPickup(bmsBusinessPickup);
				return updateRes;
			}else if(bmsBusinessPickup.getAttachmentIds() != null && bmsBusinessPickup.getAttachmentIds().size() > 0 && ("".equals(bmsBusinessPickup.getInveSurvey()) || bmsBusinessPickup.getInveSurvey()==null)) {
				int updateRes = bmsAttachmentMapper.updateBmsAttachmentByGuidsUpdateBiz(
						bmsBusinessPickup.getAttachmentIds(), bmsBusinessPickup.getGuid(),
						AttachmentConstants.BUSINESS_PICKUP, tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
				bmsAttachmentProjectBusinessService.insertBmsAttachmentProjectBusinessByBusinessId(bmsBusinessPickup.getAttachmentIds(), bmsBusinessPickup.getBusinessId());
				
				bmsBusinessPickup.setPickUpDate(DateUtils.getNowDate());
				bmsBusinessPickup.setPickUpPerson(tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getNickName());
				bmsBusinessPickupMapper.updateBmsBusinessPickup(bmsBusinessPickup);
				return updateRes;
			}else if(!"".equals(bmsBusinessPickup.getInveSurvey()) && bmsBusinessPickup.getInveSurvey()!=null && (bmsBusinessPickup.getAttachmentIds() == null || bmsBusinessPickup.getAttachmentIds().size() <= 0)) {
				
				bmsBusinessPickup.setPickUpDate(DateUtils.getNowDate());
				bmsBusinessPickup.setPickUpPerson(tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getNickName());
				bmsBusinessPickup.setInveSurvey(bmsBusinessPickup.getInveSurvey());
				bmsBusinessPickup.setPickUpExplain(bmsBusinessPickup.getPickUpExplain());
				int res = bmsBusinessPickupMapper.updateBmsBusinessPickup(bmsBusinessPickup);
				return res;
			}else {
				
				bmsBusinessPickup.setPickUpPerson(null);
				bmsBusinessPickup.setPickUpDate(null);
				bmsBusinessPickupMapper.updateBmsBusinessPickup(bmsBusinessPickup);
			}
		}
		
		return result;
	}

	/**
	 * 批量删除收资管理
	 * 
	 * @param guids 需要删除的收资管理ID
	 * @return 结果
	 * @throws Exception
	 */
	@Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public int deleteBmsBusinessPickupByGuids(String[] guids) throws Exception {
		// 首先，逻辑删除该文件标题下的所有附件
		int res = bmsAttachmentMapper.updateBmsAttachmentByGuids(guids, tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
		
		Set<String> firstSet = new HashSet<String>();
		Set<String> secondSet = new HashSet<String>();
		Collections.addAll(firstSet, guids);
		
		if(guids.length>0) {
			for(int i=0;i<guids.length;i++) {
				BmsAttachment bmsAttachment = new BmsAttachment();
				bmsAttachment.setBizId(guids[i]);
				List<BmsAttachment> resList = bmsAttachmentMapper.selectBmsAttachmentList(bmsAttachment);
				if(resList!=null && resList.size()>0) {
					for (BmsAttachment bmsAttachment2 : resList) {
						if("1".equals(bmsAttachment2.getArchiveStatus())) {
							secondSet.add(guids[i]);
							break;
						}
					}
				}
			}
			
		}
		
		firstSet.removeAll(secondSet);
		String[] newGuids = new String[firstSet.size()];
		firstSet.toArray(newGuids);
		if (res < 0)
			throw new Exception("逻辑删除文件标题下的附件失败，guids=" + newGuids);
		return bmsBusinessPickupMapper.deleteBmsBusinessPickupByGuids(newGuids);
	}

	/**
	 * 删除收资管理信息
	 * 
	 * @param guid 收资管理ID
	 * @return 结果
	 */
	@Override
	public int deleteBmsBusinessPickupByGuid(String guid) {
		return bmsBusinessPickupMapper.deleteBmsBusinessPickupByGuid(guid);
	}

	@Override
	public int importBmsBusinessPickups(List<BmsBusinessPickup> bmsBusinessPickups,String businessId) {
		//bmsProjectDocCatalogService.addDocCatalog(businessId,CatalogType.ZERO.getCode());
		return bmsBusinessPickupMapper.importBmsBusinessPickups(bmsBusinessPickups);
	}

	@Override
	public Integer selectBmsBusinessPickupListTotal(BmsBusinessPickup bmsBusinessPickup) {
		return bmsBusinessPickupMapper.selectBmsBusinessPickupListTotal(bmsBusinessPickup);
	}

	@Override
	public List<BmsBusinessPickup> getPickupByGuid(String businessId) {
		return bmsBusinessPickupMapper.getPickupByGuid(businessId);
	}

	@Override
	public List<BmsPickupTimerDto> getSendMsgInfo() {
		return bmsBusinessPickupMapper.getSendMsgInfo();
	}

	@Override
	public List<BmsBusinessPickup> selectProjectDocQueryList(BmsBusinessPickup bmsBusinessPickup) {
		return bmsBusinessPickupMapper.selectProjectDocQueryList(bmsBusinessPickup);
	}

	@Override
	public int updatePickupCounts(BmsPickupTimerDto bmsPickupTimerDto) {
		return bmsBusinessPickupMapper.updatePickupCounts(bmsPickupTimerDto);
	}
}
